package com.hzit.sb2.util.weixin;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;

@Component
public class HttpClientUtil {

    /**
     * GET获取内容
     * @param url
     * @return
     */
    public  String get(String url){
        try {
            //创建客户端对象
            HttpClient httpClient = HttpClients.createDefault();
            //发起Get请求
            HttpGet httpGet = new HttpGet(url);
            //执行get请求
            HttpResponse httpResponse = httpClient.execute(httpGet);
            //获取实体
            HttpEntity entity = httpResponse.getEntity();
            //转换字符串
            String string = EntityUtils.toString(entity, "utf-8");
            return string;
        }catch (Exception e){
            e.printStackTrace();
            System.err.println("wx-net:get方法出现异常："+e.getMessage());
        }
        return null;
    }

    /**
     * POST获取内容
     * @param url
     * @param requestBody
     * @return
     */
    public  String post(String url, String requestBody){
        try {
            HttpClient httpClient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            StringEntity stringEntity = new StringEntity(requestBody, "utf-8");
            httpPost.setEntity(stringEntity);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity entity = httpResponse.getEntity();
            //转换字符串
            String string = EntityUtils.toString(entity, "utf-8");
            return string;
        }catch (Exception e){
            e.printStackTrace();
            System.err.println("wx-net:post方法出现异常："+e.getMessage());
        }
        return null;
    }

}
